import { getArticleComment } from '@/services';
import { ICommentDetail } from '@/types';
import { Effect, Reducer } from 'umi';

export interface CommentModelState {
  commentList: ICommentDetail [];
  commentLength: number;
}

export interface CommentModelType {
  namespace: 'comment';
  state: CommentModelState;
  effects: {
    getArticleComment: Effect;
  };
  reducers: {
    save: Reducer<CommentModelState>;
  };
}

const CommentModel: CommentModelType = {
  // 数据模型，用来隔离数据防止相互影响
  namespace: 'comment',

  // 数据模型状态，相当于vuex的state
  state: {
    commentList: [],
    commentLength: 0,
  },

  // 异步操作，相当于vuex的action
  effects: {
    *getArticleComment({payload}, {call, put}){
      let result = yield call(getArticleComment, payload.id, payload.page);
      if (result.data){
        yield put({
          type: 'save',
          payload: {
            commentList: result.data[0],
            commentLength: result.data[1]
          }
        })
      }
    }
  },

  // 同步操作，相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },

  }
};

export default CommentModel;
